package com.dyx.source.reactor.multiThreadMultiReactor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class BossReactor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(BossReactor.class);

    private final String name;

    private final ServerSocketChannel serverSocketChannel;
    private final Selector selector;

    private WorkerReactor workerReactor;

    public BossReactor(String name) throws IOException {
        this.name = name;
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8082));
        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        workerReactor = new WorkerReactor("Worker");
    }



    @Override
    public void run() {
        final String threadName = Thread.currentThread().getName();
        try {
            while (true) {
                LOGGER.info("Boss[{}]在select方法之前...", threadName);
                selector.select();
                LOGGER.info("Boss[{}]在select方法之后...", threadName);
                final Set<SelectionKey> selectionKeys = selector.selectedKeys();
                final Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    final SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    if (selectionKey.isAcceptable()) {
                        final SocketChannel socketChannel = serverSocketChannel.accept();
                        LOGGER.info("接收到一个客户端连接...");
                        workerReactor.bind(socketChannel);

                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
